package com.github.xiaoymin.map.ext;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.github.xiaoymin.map.MapClientConfig;
import com.github.xiaoymin.map.model.BaiduKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class BaiduAbstractClient extends AbstractMapClient{
    /**
     * 根据开发配置构造MapClient
     *
     * @param mapClientConfig 开发配置
     */
    protected BaiduAbstractClient(MapClientConfig mapClientConfig) {
        super(mapClientConfig);
    }

    private Logger logger= LoggerFactory.getLogger(BaiduAbstractClient.class);


    /**
     * 构造请求参数
     * @param params 参数列表
     * @return 请求参数
     */
    protected String parameter(Map<String,String> params){
        StringBuilder paramBuilder=new StringBuilder();
        if (CollectionUtil.isNotEmpty(params)){
            ConcurrentHashMap<String,String> newParams= MapUtil.newConcurrentHashMap(params);
            List<String> paramsArr=new ArrayList<>();
            for (Map.Entry<String,String> entry:newParams.entrySet()){
                paramsArr.add(entry.getKey()+"="+entry.getValue());
            }
            paramBuilder.append(CollectionUtil.join(paramsArr,"&"));
        }
        String parameter=paramBuilder.toString();
        if (StrUtil.isNotBlank(parameter)){
            logger.info("参数编码前:{}",parameter);
            parameter= URLUtil.encode(parameter);
        }
        logger.info("请求参数:{}",parameter);
        return parameter;
    }

    /**
     * 对于请求参数Map追加接口秘钥key
     * @param param
     * @param baiduKey
     * @return
     */
    protected Map<String,String> appendKey(Map<String,String> param, BaiduKey baiduKey){
        param.put("ak",baiduKey.getAk());
        return param;
    }
}
